import 'package:collection/collection.dart';
import 'package:mall/core/models/product_detail.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/core/providers/pages/store/product_detail_model.dart';
import 'package:mall/core/providers/view_model.dart';

/// 加入购物车
class ProductOptionModel extends ViewModel {
  final Api api;
  final ProductDetail productDetail;
  final Map<String, int> _currentSku;
  int _quantity;

  ProductOptionModel(this.api, ProductDetailModel model)
      : productDetail = model.productDetail,
        _currentSku = {}..addAll(model.productDetail.currentSku),
        _quantity = model.productDetail.defaultMia.minPurchaseAmount,
        super();

  int get quantity => _quantity;

  set quantity(int value) {
    // 需要判断能不能修改
    final mia = queryMia();
    final min = mia.minPurchaseAmount;
    var max = mia.maxAmount;
    if (max <= 0) {
      max = 100000;
    }
    if (mia.enableModify && min <= value && value <= max) {
      _quantity = value;
      notifyListeners();
    }
  }

  /// 获取当前Sku
  Sku querySku() {
    return productDetail.skus.firstWhere(
      (element) => MapEquality().equals(
        element.sku,
        _currentSku,
      ),
      orElse: () => productDetail.skus.firstWhere(
        (element) => MapEquality().equals(
          element.sku,
          productDetail.currentSku,
        ),
      ),
    );
  }

  /// 获取当前Mia
  Mia queryMia() {
    // 根据currentSku查询miaId
    var sku = querySku();
    // 查询有没有Mia
    return productDetail.allMia.firstWhere(
      (element) => element.id == sku.miaId,
      orElse: () => productDetail.defaultMia,
    );
  }

  /// 判断可选与否
  bool selectable(Option option, OptionValue optionValue) {
    for (Sku sku in productDetail.skus) {
      var currentSkuTemp = {}..addAll(_currentSku);
      currentSkuTemp[option.id.toString()] = optionValue.id;
      var isSub = currentSkuTemp.entries.every(
        (mapEntry) => DeepCollectionEquality().equals(
          mapEntry.value,
          sku.sku[mapEntry.key],
        ),
      );
      if (isSub) {
        return true;
      }
    }
    return false;
  }

  /// 获取是否选择
  bool selected(Option option, OptionValue optionValue) {
    var mapEntry = _currentSku.entries.firstWhere(
      (element) => element.key == option.id.toString() && element.value == optionValue.id,
      orElse: () => null,
    );
    return mapEntry != null;
  }

  /// 切换选择
  void toggle(Option option, OptionValue optionValue) {
    var mapEntry = _currentSku.entries.firstWhere(
      (element) => element.key == option.id.toString() && element.value == optionValue.id,
      orElse: () => null,
    );
    if (mapEntry == null) {
      _currentSku[option.id.toString()] = optionValue.id;
    } else {
      _currentSku.remove(option.id.toString());
    }
    // 更新一下默认数量
    final mia = queryMia();
    _quantity = mia.minPurchaseAmount;
    // 更新
    notifyListeners();
  }
}
